<?php

namespace app\index\controller;

use app\common\controller\Frontend;

class Article extends Frontend
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $layout = 'default';

    public function _initialize()
    {
        parent::_initialize();

        // 获取当前控制器和方法
        $controller = strtolower($this->request->controller());
        $action = strtolower($this->request->action());

        // 获取分类列表（用于导航栏）
        $categoryModel = new \app\common\model\ArticleCategory;
        $categoryList = $categoryModel->select();

        $this->view->assign([
            'controller' => $controller,
            'action' => $action,
            'categoryList' => $categoryList,
        ]);
    }

    public function index()
    {
        $categoryId = $this->request->param('category_id', '');

        $where = ['status' => \app\common\model\Article::STATUS_NORMAL];
        if ($categoryId) {
            $where['category_id'] = $categoryId;
        }

        $articleModel = new \app\common\model\Article;

        $this->view->assign([
            'list' => $articleModel->where($where)->order(['weigh' => 'desc', 'created_at' => 'desc'])->paginate(),
            'category_id' => $categoryId,
        ]);

        return $this->view->fetch();
    }

    public function detail($id)
    {
        $detail = \app\common\model\Article::get($id);
        if (!$detail) {
            $this->error('文章不存在');
        }

        // 检查文章状态
        if ($detail['status'] != \app\common\model\Article::STATUS_NORMAL) {
            $this->error('文章已下架');
        }

        // 增加浏览量
        $detail->incrementViews($this->request->ip());

        $this->view->assign('detail', $detail);
        return $this->view->fetch();
    }
}
